import { ConfigEnv, defineConfig, loadEnv, UserConfig } from 'vite'

import alias from './vite/alias'
import setupPlugins from './vite/plugins/index'
import { parseEnv } from './vite/utils'

const userConfigFnObject = (env: ConfigEnv): UserConfig => {
  const { mode, command } = env
  const isBuild = command === 'build'
  const viteEnv = parseEnv(loadEnv(mode, process.cwd()))
  return {
    base: '',
    plugins: setupPlugins(isBuild, viteEnv),
    resolve: {
      alias,
    },
    server: { host: '0.0.0.0' },
    build: {
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true,
        },
        format: {
          comments: false, // 删除所有注释
        },
      },
      chunkSizeWarningLimit: 2000,
      cssCodeSplit: true,
      sourcemap: false,
      assetsInlineLimit: 5000,
      target: 'modules',
      outDir: 'dist',
      assetsDir: 'assets',
      rollupOptions: {
        output: {
          chunkFileNames: 'js/[name]-[hash].js',
          entryFileNames: 'js/[name]-[hash].js',
          assetFileNames: '[ext]/[name]-[hash].[ext]',
          manualChunks(id) {
            if (id.includes('node_modules')) {
              return id.toString().split('node_modules/')[1].split('/')[0].toString()
            }
          },
        },
      },
    },
  }
}

// https://vitejs.dev/config/
export default defineConfig(userConfigFnObject)
